import sys,os,shutil,re,platform
if platform.system()[0]!="W":
    rm="rm "
else:
    rm="del "
    
def checkpath(p,w=(rm!="rm ")):
    a=p.split(os.sep)
    b=[]
    for i in a:
        if not w:
            if " " in i:
                i=i.replace(" ","\\ ").replace("\\\\ ","\\ ")
        else:
            if " " in i and i[0]!="\"" and i[-1]!="\"":
                i="\""+i+"\""
        b.append(i)
    return os.sep.join(b)
    
def restorepath(p):
    a=p.split(os.sep)
    b=[]
    for i in a:
        if " " in i:
            i=i.replace("\\ "," ")
            if i[0]=="\"" and i[-1]=="\"":
                i=i[1:-1]
        b.append(i)
    return os.sep.join(b)

paths = ["", os.sep.join(sys.argv[0].split(os.sep)[:-1])+os.sep, "/etc/"]
for p in paths:
    if os.path.isfile(p+"tcrun.conf"):
        f=file(p+'tcrun.conf','r')
        break
if 'f' not in locals():
    print "Error reading configuration file!"
    sys.exit(1)
a=f.read().replace('\r','').split('\n')
f.close()

tcpath=re.findall('TC=(.+)',a[0])
if len(tcpath)==0:
    print "Error format in tcrun.conf! Configuration should be like TC=<TurboCPath>."
    sys.exit(1)
tcpath=checkpath(tcpath[0])
if tcpath[-1]!=os.sep:
    tcpath+=os.sep

dbpath=re.findall('DOSBOX=(.*)',a[1])
if len(dbpath)==0:
    print "Error format in tcrun.conf! Configuration should be like DOSBOX=<TurboCPath>."
    sys.exit(1)
dbpath=checkpath(dbpath[0])
if len(dbpath)>0 and dbpath[-1]!=os.sep:
    dbpath+=os.sep

cr=os.getcwd()
fo=sys.argv[1]
if cr[-1]!=os.sep:
    cr+=os.sep
if fo[0]!='/' and ':\\' not in sys.argv[1]:
    fo=cr+sys.argv[1]
else:
    fo=sys.argv[1]
fo=checkpath(fo)
fn1=".".join(fo.split('.')[:-1]).split(os.sep)[-1][:8]
fn=checkpath(tcpath+"BIN"+os.sep+fn1+'.c')
fp=checkpath(os.sep.join(fn.split(os.sep)[:-1])+os.sep)

if not os.path.isfile(restorepath(tcpath)+"BIN"+os.sep+"run.bat"):
    f=file(restorepath(tcpath)+"BIN"+os.sep+"run.bat","w")
    m="@echo off\ncls\ntcc.exe -IC:\INCLUDE -LC:\LIB -nC:\BIN -w C:\BIN\%1.c graphics.lib\n%1\npause\nexit"
    f.write(m)
    f.close()

if os.path.isfile(restorepath(fn)):
    os.system(rm+fn)
    os.system(rm+fp+fn1.upper()+".EXE")
#sys.exit(0)
shutil.copy(restorepath(fo),restorepath(fn))
m="[autoexec]\nmount c \""+restorepath(tcpath)+"\"\nc:\ncd BIN\nrun "+fn1
f=file(restorepath(tcpath)+"dosboxnew.conf","w")
f.write(m)
f.close()
#print dbpath+'dosbox -conf "'+restorepath(tcpath)+'dosboxnew.conf"'
os.system(dbpath+'dosbox -conf "'+restorepath(tcpath)+'dosboxnew.conf"')

